# log_service.py
import sqlite3
from datetime import datetime

# 在文件顶部添加导入
from utils.config_manager import config

class LogService:
    def __init__(self, db_path=None):
        self.db_path = db_path if db_path else config.get_db_path()
        self._create_table()

    def _create_table(self):
        """确保sh_log表存在（带自增id和用户ID）"""
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("""
                CREATE TABLE IF NOT EXISTS sh_log (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    userId TEXT NOT NULL,
                    contentType TEXT NOT NULL,
                    content TEXT,
                    createTime TEXT DEFAULT (DATETIME('now', 'localtime'))
                )
            """)

    def save_log(self, content_type: str, content: str, user_id: str = '2'):
        """
        写入日志到sh_log表
        :param user_id: 用户ID（必须）
        :param content_type: 日志类型（如：操作日志、错误日志等）
        :param content: 日志内容
        """
        with sqlite3.connect(self.db_path) as conn:
            conn.execute(
                "INSERT INTO sh_log (userId, contentType, content) VALUES (?, ?, ?)",
                (user_id, content_type, content)
            )

    def get_logs_by_user_and_type(self, content_type: str, user_id: str='2', limit: int = 100):
        """
        根据用户和类型查询日志
        :param user_id: 要查询的用户ID
        :param content_type: 要查询的日志类型
        :param limit: 最大返回条数
        :return: 按时间倒序排列的日志列表，格式：[ (createTime, content), ... ]
        """
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.execute(
                "SELECT createTime, content FROM sh_log "
                "WHERE userId = ? AND contentType = ? "
                "ORDER BY createTime DESC LIMIT ?",
                (user_id, content_type, limit)
            )
            return cursor.fetchall()

    def get_recent_logs_by_user(self, user_id: str = '2', days: int = 7):
        """
        获取用户最近N天的日志
        :param user_id: 用户ID
        :param days: 最近天数
        :return: 日志列表，格式：[ (createTime, contentType, content), ... ]
        """
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.execute(
                "SELECT createTime, contentType, content FROM sh_log "
                "WHERE userId = ? AND date(createTime) >= date('now', '-? days') "
                "ORDER BY createTime DESC",
                (user_id, days)
            )
            return cursor.fetchall()


# 使用示例
if __name__ == "__main__":
    service = LogService()

    # 写入日志（需要指定用户ID）
    service.save_log("1001", "登录", "用户admin登录系统")
    service.save_log("1002", "操作", "修改了配置参数")

    # 查询用户1001的操作日志
    logs = service.get_logs_by_user_and_type(1001, "操作")
    for log in logs:
        print(f"[{log[0]}] {log[1]}")
